package com.ccit.goods.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.client.GoodsClient;
import com.ccit.common.client.IntegralClient;
import com.ccit.common.client.MoneyClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.goods.service.GoodsOrderService;
import com.ccit.goods.service.GoodsService;
import com.ccit.model.Goods;
import com.ccit.model.GoodsOrder;
import com.ccit.model.Integral;
import com.ccit.model.vo.goodsOrder.GoodsOrderResultVo;
import com.ccit.model.vo.goodsOrder.GoodsOrderVo;
import com.ccit.model.vo.money.MoneyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "商品订单管理")
@RestController
@RequestMapping("/goodsOrder")
public class GoodsOrderController {
    @Autowired
    private GoodsOrderService goodsOrderService;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private IntegralClient integralClient;

    @Autowired
    private MoneyClient moneyClient;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisUtils redisUtils;

    @ApiOperation("分页获取商品订单")
    @GetMapping("/getByPage/{current}/{size}")
    public Result getGoodsOrderByPage (@PathVariable Integer current, @PathVariable Integer size){
        String key = "allGoodsOrder";
        boolean hasKey = redisUtils.hasKey(key);
        List<GoodsOrder> allOrder;
        if (hasKey){
            System.out.println("===================redis=====================");
            allOrder = (List<GoodsOrder>)redisUtils.get(key);
        }else {
            allOrder = goodsOrderService.findAllOrder();
            redisUtils.set(key,allOrder);
        }
        Page pages = PageUtil.getPages(current, size, allOrder);
        return Result.ok(pages);
    }

    @GetMapping("/getByPage/{current}/{size}/{phone}")
    @ApiOperation(value = "根据手机号查询订单(分页)")
    public Result selectOrderByPhone(@PathVariable("current") Integer current,
                                     @PathVariable("size") Integer size,
                                     @PathVariable("phone") String phone) {
        String key = "goodsOrderPhone:"+ phone;
        boolean hasKey = redisUtils.hasKey(key);
        List<GoodsOrder> orderByPhone;
        if (hasKey){
            System.out.println("===================redis=====================");
            orderByPhone = (List<GoodsOrder>)redisUtils.get(key);
        }else {
            orderByPhone = goodsOrderService.findGoodsOrderByPhone(phone);
            if (orderByPhone==null){
                throw new GymException(202,"查无此手机用户订单");
            }
            redisUtils.set(key,orderByPhone);
        }
        Page pages = PageUtil.getPages(current, size, orderByPhone);
        return Result.ok(pages);
    }


    @ApiOperation(value = "添加新订单")
    @PostMapping("/saveOrder")
    public Result saveOrder(@RequestBody GoodsOrder order) {
        Goods goodsById = goodsClient.getGoodsById(order.getGoodsId());
        if (goodsById==null){
            throw new GymException(202,"无此商品");
        }
        if (goodsById.getStock()-order.getNum()>=0){
            goodsById.setStock(goodsById.getStock()-order.getNum());
            System.out.println("--------------------"+goodsById+"====================================");
            goodsClient.updateGoods(goodsById);
            order.setCost(order.getNum()*goodsById.getPrice());
            order.setGoodsName(goodsById.getName());

            Boolean saveOrder = goodsOrderService.saveOrder(order);
            if (saveOrder){
                Integral integral = new Integral();
                integral.setIntegral((int)(Math.round(order.getCost()*order.getNum()/100)));
                integral.setPhone(order.getPhone());
                Boolean b = integralClient.updateIntegral(integral);
                if (!b){
                    throw new GymException(202,"更新积分出错");
                }
                MoneyVo moneyVo = new MoneyVo();
                moneyVo.setMoneyType("收入");
                moneyVo.setTypeName("商品订单");
                moneyVo.setAmout(order.getCost());
                boolean b1 = moneyClient.apiSaveMoney(moneyVo);
                if (!b1){
                    throw new GymException(301,"添加商品订单资金记录失败");
                }
                redisUtils.deleteRedisKeys("goodsOrderPhone");
                redisUtils.deleteRedisKeys("allGoodsOrder");
                redisUtils.deleteRedisKeys("goodsOrder");
                redisUtils.deleteRedisKeys("GoodsPage");
                return Result.ok();
            }else return Result.fail();
        }else return Result.fail().message("库存不足");
    }
    @ApiOperation(value = "条件查询")
    @PostMapping("/getByDynamic/{current}/{size}")
    public Result getByDynamic(
            @RequestBody GoodsOrderVo goodsOrderVo,
            @PathVariable Integer current,
            @PathVariable Integer size) {
        String key = "goodsOrder";
        if (goodsOrderVo.getPhone() != null){
            key = key + ":" + goodsOrderVo.getPhone();
        }
        if (goodsOrderVo.getName()!=null){
            key = key + ":" + goodsOrderVo.getName();
        }
        boolean hasKey = redisUtils.hasKey(key);
        List<GoodsOrderResultVo> resultVos = new ArrayList<>();

        if (hasKey){
            System.out.println("===================redis=====================");
            resultVos = (List<GoodsOrderResultVo>)redisUtils.get(key);
        }else {
            //根据商品名查商品id
            if (goodsOrderVo.getName()!=null){
                Goods goodsByName = goodsClient.getGoodsByName(goodsOrderVo.getName());
                goodsOrderVo.setGoodsId(goodsByName.getId());
            }
            List<GoodsOrder> list = new ArrayList<>();
            //根据手机号和商品id查商品订单
            if (goodsOrderVo.getPhone() != null){
                if (goodsOrderVo.getGoodsId() != null){
                    list = goodsOrderService.findGoodsOrderByGoodsIdAndPhone(goodsOrderVo.getGoodsId(),goodsOrderVo.getPhone());
                }else {
                    list = goodsOrderService.findGoodsOrderByPhone(goodsOrderVo.getPhone());
                }
            }else if (goodsOrderVo.getGoodsId() != null){
                list = goodsOrderService.findGoodsOrderByGoodsId(goodsOrderVo.getGoodsId());
            }else {
                list = goodsOrderService.findAllOrder();
            }

            //将查询商品订单数据与商品一起封装
            List<GoodsOrderResultVo> resultVoss = new ArrayList<>();
            list.forEach(goodsOrder -> {
                GoodsOrderResultVo resultVo = new GoodsOrderResultVo();
                System.out.println(goodsOrder);
                Goods goods = goodsClient.getGoodsById(goodsOrder.getGoodsId());
                System.out.println(goods);
                resultVo.setGoods(goods);
                resultVo.setGoodsId(goods.getId());
                resultVo.setGoodsName(goodsOrder.getGoodsName());
                resultVo.setCost(goodsOrder.getCost());
                resultVo.setId(goodsOrder.getId());
                resultVo.setPhone(goodsOrder.getPhone());
                resultVo.setNum(goodsOrder.getNum());
                resultVo.setTime(goodsOrder.getTime());
                resultVoss.add(resultVo);
            });
            resultVos = resultVoss;
            redisUtils.set(key,resultVos);
        }
        Page page = PageUtil.getPages(current, size, resultVos);

        return Result.ok(page);
    }

    @ApiOperation(value = "获取所有手机号")
    @GetMapping("/getAllPhone")
    public Result getAllPhone() {
        String key = "goodsOrderPhoneList";
        boolean hasKey = redisUtils.hasKey(key);
        List<Map> phoneList ;
        if (hasKey) {
            System.out.println("==================redis========================");
            phoneList =(List<Map>)redisUtils.get(key);
        } else {
            List<GoodsOrder> allOrder = goodsOrderService.findAllOrder();
            Map<String, List<GoodsOrder>> collect = allOrder.stream().collect(Collectors.groupingBy(goodsOrder -> goodsOrder.getPhone()));
            phoneList = new ArrayList<>();
            collect.forEach((s,value)->{
                Map<String , String> phone = new HashMap<>();
                System.out.println(s);
                phone.put("value",s);
                phoneList.add(phone);
            });
            redisUtils.set(key, phoneList);
        }
        return Result.ok(phoneList);

    }

    //mysql转mongodb
   /* @GetMapping("/get")
    public Result selectOrderMysql(){
        List<GoodsOrder> list = goodsOrderService.list();
        list.forEach(order -> {
            goodsOrderService.saveOrder(order);
        });
        List<GoodsOrder> allOrder = goodsOrderService.findAllOrder();
        return Result.ok(allOrder);
    }*/

    @GetMapping("/get")
    public Result selectOrder(@RequestBody GoodsOrder goodsOrder){

        List<GoodsOrder> list = goodsOrderService.findGoodsOrderList(goodsOrder);

        return Result.ok(list);
    }
}
